package com.star.uc.contract.enums.uid;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.lang.Snowflake;
import com.star.common.core.context.SpringContext;
import com.star.common.core.contract.constant.ContextConstants;
import com.star.common.kit.date.DateUtil;
import com.star.uc.contract.constant.UserRedisConstants;
import com.star.uc.infras.properties.SaTokenProperties;
import com.star.uc.infras.utils.RedisUtils;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.Date;

/**
 * 生成用户ID的类型
 *
 * @author zhouhengzhe
 * @version 1.0
 * @date 2023/10/23 15:51
 */
@Getter
@AllArgsConstructor
public enum GeneratorUidTypeEnum implements Generator {
    AUTO("AUTO", "AUTO", "默认为uuid随机算法") {
        /**
         * 生成UID（34位）
         *
         * @return
         */
        @Override
        public String generatorUid() {
            return UUID.generatorUid();
        }
    },
    UUID("UUID", "UUID", "UUID随机算法") {
        /**
         * 生成UID(34位)
         *
         * @return
         */
        @Override
        public String generatorUid() {
            return ContextConstants.UUID_PREFIX + cn.hutool.core.lang.UUID.randomUUID().toString().replaceAll("-", "");
        }
    },
    REDIS("REDIS", "REDIS", "redis有序生成") {
        /**
         * 生成UID(22位)
         *
         * @return
         */
        @Override
        public String generatorUid() {
            //14位,生成14位时间格式：yyyyMMddHHmmss
            String currentDate = DateUtil.dateToString(new Date(), DatePattern.PURE_DATETIME_PATTERN);
            //6位,生成6位固定数字
            String uuid = SpringContext.getBean(RedisUtils.class).generator(UserRedisConstants.USER_GENERATOR_UID + currentDate, 1, 1, 6);
            return ContextConstants.UUID_PREFIX + currentDate + uuid;
        }
    },
    ASSIGN_ID("ASSIGN_ID", "ASSIGN_ID", "雪花算法") {
        /**
         * 生成UID(21位)，有其他需求可自行更改
         *
         * @return
         */
        @Override
        public String generatorUid() {
            Snowflake snowflake = new Snowflake();
            return ContextConstants.UUID_PREFIX + snowflake.nextIdStr();
        }
    };

    private final String type;
    private final String realType;
    private final String desc;

    /**
     * 生成用户ID
     *
     * @return
     */
    public static String getUidByType() {
        String type = SpringContext.getBean(SaTokenProperties.class).getGeneratorUidType();
        for (GeneratorUidTypeEnum generatorUidTypeEnum : GeneratorUidTypeEnum.values()) {
            if (generatorUidTypeEnum.getType().equals(type)) {
                return generatorUidTypeEnum.generatorUid();
            }
        }
        return AUTO.generatorUid();
    }
}
